const app = getApp()
// const url = 'iosamap://path?sourceApplication=applicationName&sid=&slat=&slon=&sname=我的位置&did=&dlat=23.141782&dlon=113.34094&dname=鸿翔大厦&dev=0&t=0&vian=2&vialons=113.289526|113.320202&vialats=23.139652|23.140079&vianames=途径点1|途径点2'

const iosUrl = 'iosamap://path?sourceApplication=applicationName&sid=&slat=&slon=&sname=我的位置&did=&t=0&'
const androidUrl = 'amapuri://route/plan/?sid=&slat=&slon=&sname=我的位置&did=&t=0&'

// 谷歌地图URL schemes
const googleMapsIosUrl = 'comgooglemaps://?'
const googleMapsAndroidUrl = 'google.navigation:'
const googleMapsWebUrl = 'https://maps.google.com/maps?'
Page({
  data: {
    popupOpened: false,
    pageNum: 0,
    tableData: [],
    totalSize: 0,
    actived: 0,
    searchDisplay: false,
    moreBtnDispaly: false,
    search: '',
    tableData: [],
    user: {}
  },
  handleSearchDisplay() {
    const { searchDisplay } = this.data
    this.setData({
      searchDisplay: !searchDisplay,
      search: ''
    })
  },
  handleSearch() {
    if (!this.data.search) {
      wx.navigateBack()
    } else {
      wx.navigateTo({
        url: `/pages/search/index?search=${this.data.search}`,
      })
    }
  },
  handleClear() {
    this.setData({
      search: ''
    })
  },
  handleDelete(e) {
    const { item } = e.target.dataset
    const data = this.data.tableData.filter(v => (item.customerNumber + item.address) !== (v.customerNumber + v.address))
    this.setData({
      tableData: data
    })
    wx.setStorageSync('itinerary', data)
  },
  filterDate() {
    this.setData({
      popupOpened: true
    })
  },
  confirm(e) {
    this.setData({
      tableData: [],
      pageNum: 0
    })
    this.init()
  },
  async init() {
    const user = app.globalData.user
    if (user.role === '销售') {
      wx.reLaunch({
        url: '/pages/form/index'
      })
    }
    const date = wx.getStorageSync('date')
    const today = new Date().getMonth() + '-' + new Date().getDate()
    console.log(today, date)
    if (date !== today ) {
      wx.removeStorageSync('itinerary')
      wx.setStorageSync('date', today)
    }
    const tableData = wx.getStorageSync('itinerary') || []
    this.setData({ tableData, user })
  },

  submit() {
    const dlon = this.data.tableData[0].vialons
    const dlat = this.data.tableData[0].vialats
    const dname = this.data.tableData[0].address
    const vialons = []
    const vialats = []
    const vianames = []
    this.data.tableData.forEach((item, i) => {
      if (i < 1) return
      vialats.push(item.vialats)
      vialons.push(item.vialons)
      vianames.push(item.customerName)
    })
    const baseUrl = app.globalData.deviceId.includes('iOS') ? iosUrl : androidUrl
    const _url = baseUrl + 'vialons=' + vialons.join('|') + '&vialats=' + vialats.join('|') + '&vianames=' + vianames.join('|') + '&dlon=' + dlon + '&dlat=' + dlat + '&dname=' +dname + '&vian=' + (this.data.tableData.length - 1)

    // 尝试直接打开地图应用
    wx.navigateToMiniProgram({
      appId: 'wxd4018c7a66d95647', // 高德地图小程序appId
      path: 'pages/index/index',
      extraData: {
        url: _url
      },
      success: () => {
        console.log('成功打开高德地图小程序')
      },
      fail: () => {
        // 如果小程序调用失败，回退到webview方式
        wx.navigateTo({
          url: '/pages/webview/webview?url=' + encodeURIComponent(_url),
        })
        wx.setClipboardData({
          data: _url,
          success: () => {
            wx.showModal({
              title: '复制成功',
              content: '地图链接已复制，请在浏览器中打开或安装对应地图应用！',
            })
          }
        })
      }
    })
  },

  // 调用谷歌地图
  submitGoogleMaps() {
    const dlon = this.data.tableData[0].vialons
    const dlat = this.data.tableData[0].vialats
    const dname = this.data.tableData[0].address

    // 构建谷歌地图URL
    const destination = `${dlat},${dlon}`
    const waypoints = []

    this.data.tableData.forEach((item, i) => {
      if (i < 1) return
      waypoints.push(`${item.vialats},${item.vialons}`)
    })

    let googleUrl = ''
    if (app.globalData.deviceId.includes('iOS')) {
      // iOS谷歌地图
      googleUrl = `${googleMapsIosUrl}daddr=${destination}&waypoints=${waypoints.join('|')}`
    } else {
      // Android谷歌地图
      googleUrl = `${googleMapsAndroidUrl}q=${destination}&waypoints=${waypoints.join('|')}`
    }

    // 网页版谷歌地图作为备选
    const webUrl = `${googleMapsWebUrl}destination=${destination}&waypoints=${waypoints.join('|')}`

    // 尝试打开谷歌地图
    wx.navigateTo({
      url: '/pages/webview/webview?url=' + encodeURIComponent(webUrl),
    })

    wx.setClipboardData({
      data: googleUrl,
      success: () => {
        wx.showModal({
          title: '复制成功',
          content: '谷歌地图链接已复制，请在浏览器中打开或安装谷歌地图应用！',
        })
      }
    })
  },

  // 使用微信原生地图
  submitWechatMap() {
    const destination = this.data.tableData[0]
    wx.openLocation({
      latitude: parseFloat(destination.vialats),
      longitude: parseFloat(destination.vialons),
      name: destination.address,
      address: destination.address,
      scale: 18,
      success: () => {
        console.log('成功打开微信地图')
      },
      fail: (err) => {
        console.error('打开微信地图失败', err)
        wx.showToast({
          title: '打开地图失败',
          icon: 'none'
        })
      }
    })
  },

  handleUpload(e) {
    const { item } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/upload/index?params=' + encodeURIComponent(JSON.stringify(item)),
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init()
    const token = wx.getStorageSync('token') || app.globalData.token
    if (!token) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
    }
  },
  onShow() {
    this.init()
  }
})